package com.it.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.aiReportClaim.ReportClaimApi;
import com.it.entity.aiClaimRegistration.AiClaimRegistration;
import com.it.mapper.AiClaimRegistrationMapper;
import com.it.service.AiClaimRegistrationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.R;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 理赔立案信息表（查勘后符合标准的立案记录） 服务实现类
 * </p>
 *
 * @author sunwz
 * @since 2025年09月20日
 */
@Service
public class AiClaimRegistrationServiceImpl extends ServiceImpl<AiClaimRegistrationMapper, AiClaimRegistration> implements AiClaimRegistrationService {

    @Autowired
    private AiClaimRegistrationMapper aiClaimRegistrationMapper;

    @Autowired
    private ReportClaimApi reportClaimApi;

    @Override
    public R list(int pageNum, int pageSize, String registrationId, String reportId, Integer status) {
        // 使用PageHelper设置分页参数
        PageHelper.startPage(pageNum, pageSize);

        // 创建LambdaQueryWrapper，使用Lambda表达式避免硬编码字段名
        LambdaQueryWrapper<AiClaimRegistration> queryWrapper = new LambdaQueryWrapper<>();

        // 立案号模糊查询（忽略空值）
        if (StringUtils.isNotBlank(registrationId)) {
            queryWrapper.like(AiClaimRegistration::getRegistrationId, registrationId);
        }

        // 报案号模糊查询（忽略空值）
        if (StringUtils.isNotBlank(reportId)) {
            queryWrapper.like(AiClaimRegistration::getReportId, reportId);
        }

        // 立案状态精确匹配（忽略空值）
        if (status != null) {
            queryWrapper.eq(AiClaimRegistration::getRegistrationStatus, status);
        }


        // 执行查询，PageHelper会自动拦截并处理分页
        List<AiClaimRegistration> aiClaimRegistrationList = aiClaimRegistrationMapper.selectList(queryWrapper);

        return R.Success("查询成功", new PageInfo<>(aiClaimRegistrationList));
    }

    @Override
    public R getByRegistrationId(String registrationId) {
        // 创建LambdaQueryWrapper，使用Lambda表达式避免硬编码字段名
        LambdaQueryWrapper<AiClaimRegistration> queryWrapper = new LambdaQueryWrapper<>();

        // 立案号精准查询（忽略空值）
        if (StringUtils.isNotBlank(registrationId)) {
            queryWrapper.eq(AiClaimRegistration::getRegistrationId, registrationId);
        }
        AiClaimRegistration aiClaimRegistration = aiClaimRegistrationMapper.selectOne(queryWrapper);
        if (aiClaimRegistration != null) {
            return R.Success("查询详情成功",aiClaimRegistration);
        }
        return R.Failed("查询详情失败");
    }

    @Override
    public R DeleteById(String registrationId) {
        // 创建LambdaQueryWrapper，使用Lambda表达式避免硬编码字段名
        LambdaQueryWrapper<AiClaimRegistration> queryWrapper = new LambdaQueryWrapper<>();

        // 立案号精准查询（忽略空值）
        if (StringUtils.isNotBlank(registrationId)) {
            queryWrapper.eq(AiClaimRegistration::getRegistrationId, registrationId);
        }
        AiClaimRegistration aiClaimRegistration = aiClaimRegistrationMapper.selectOne(queryWrapper);
        if (aiClaimRegistration != null) {
            aiClaimRegistrationMapper.delete(queryWrapper);
            return R.Success("该记录已删除");
        }
        return R.Failed("该记录不存在");
    }

    @Override
    public R updateStatus(String registrationId, Integer status,String cancelReason) {
        // 创建LambdaQueryWrapper，使用Lambda表达式避免硬编码字段名
        LambdaQueryWrapper<AiClaimRegistration> queryWrapper = new LambdaQueryWrapper<>();

        // 立案号精准查询（忽略空值）
        if (StringUtils.isNotBlank(registrationId)) {
            queryWrapper.eq(AiClaimRegistration::getRegistrationId, registrationId);
        }
        AiClaimRegistration aiClaimRegistration = aiClaimRegistrationMapper.selectOne(queryWrapper);
        if (aiClaimRegistration != null) {
            aiClaimRegistration.setRegistrationStatus(status);
            if(StringUtils.isNotBlank(cancelReason)){
                aiClaimRegistration.setCancelReason(cancelReason);
            }

            aiClaimRegistrationMapper.updateById(aiClaimRegistration);
            return R.Success("修改状态成功");
        }
        return R.Failed("失败");
    }

    @Transactional
    @Override
    public R insert(AiClaimRegistration aiClaimRegistration) {

        aiClaimRegistration.setRegistrationId(generateRegistrationId());

        aiClaimRegistration.setRegistrationTime(LocalDateTime.now());

        int a = aiClaimRegistrationMapper.insert(aiClaimRegistration);

        if (a != 0) {

         reportClaimApi.updateStatus(aiClaimRegistration.getReportId(), 4);

        return R.Success("新增立案信息成功");
        }
        return R.Failed("新增失败");
    }

    @Override
    public R getByReportNo(String reportNo) {
        LambdaQueryWrapper<AiClaimRegistration> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AiClaimRegistration::getReportId, reportNo);
        AiClaimRegistration aiClaimRegistration = aiClaimRegistrationMapper.selectOne(queryWrapper);
        return R.Success("查询成功",aiClaimRegistration);
    }

    @Override
    public R select(String policyId) {

        LambdaQueryWrapper<AiClaimRegistration> queryWrapper = new LambdaQueryWrapper<>();

        if(policyId!=null && !policyId.isEmpty()){
            queryWrapper.eq(AiClaimRegistration::getPolicyId,policyId);
        }
        AiClaimRegistration aiClaimRegistration = aiClaimRegistrationMapper.selectOne(queryWrapper);

        return R.Success("查询成功",aiClaimRegistration);
    }

    /**
     * 生成立案编号
     * 格式：INS+yyyyMMdd+6位随机数，例如：INS20250918123456
     */
    private String generateRegistrationId() {
        // 前缀
        String prefix = "REG";
        // 日期部分：年月日
        String datePart = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 随机数部分：6位随机数
        String randomPart = String.format("%06d", new Random().nextInt(1000000));

        // 组合生成保单编号
        return prefix + datePart + randomPart;
    }

}

